import 'dart:async';

import 'dart:ui' as ui;

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart' as material;

import 'package:html/parser.dart' show parse;
import 'package:html/dom.dart';

class ImageHolder {
  String url;
  double ratio = 0;
}

class HtmlUtil {
  static Future<List<dynamic>> parseHtml(String htmlStr) async {
    if (htmlStr == null && htmlStr.trim() != '') return null;
    List<String> html = [];
    Document document = parse(htmlStr);
    _parseElement(html, document.body);
    return html;
    if (html.length > 0) {
      List<dynamic> list = [];
      Map<String, bool> map = {};
      for (String str in html) {
        if (str.startsWith('http')) {
          map[str] = false;
          Completer<dynamic> completer = Completer.sync();
          CachedNetworkImageProvider(str + '?x-oss-process=image/format,webp')
              .resolve(material.ImageConfiguration())
              .addListener(material.ImageStreamListener((material.ImageInfo info, synchronousCall) {
                if (map[str] != null && map[str]) return;
                map[str] = true;
                completer.complete(info.image);
              }, onError: (error, stack) {
                if (map[str] != null && map[str]) return;
                map[str] = true;
                completer.complete(null);
              }));
          ui.Image data;
          try {
            data = await completer.future;
          } catch (e) {
            print(e);
          }
          ImageHolder holder = ImageHolder();
          holder.url = str;
          if (data != null) {
            if (data is ui.Image) {
              holder.ratio = data.width / data.height;
            }
          }
          list.add(holder);
        } else {
          list.add(str);
        }
      }
      return list;
    } else {
      return null;
    }
  }

  static void _parseElement(List<String> data, Element element) {
    for (var child in element.nodes) {
      if (child is Element) {
        switch (child.localName) {
          case 'strong':
          case 'span':
            String parent = child?.parent?.localName;
            if (!(parent != null &&
                parent.trim() != '' &&
                (parent == 'span' || parent == 'strong'))) {
              String content = child.text;
              if (content != null && content.trim() != '') {
                data.add(content);
              }
            }
            break;
          case 'img':
            if (child.attributes.containsKey('src')) {
              data.add(child.attributes['src']);
            }
            break;
        }
        _parseElement(data, child);
      }
    }
  }
}
